<template>
  <div class="container">
    <Breadcrumb :items="['menu.setting', 'menu.setting.config']" />
    <a-card class="general-card" :title="$t('menu.setting.config')">
      <a-row>
        <a-col :flex="1">
          <!-- 搜索 -->
          <a-form ref="searchFormRef" :model="searchForm" auto-label-width>
            <a-row :gutter="24">
              <a-col :span="6">
                <a-form-item :label="$t('config.form.name')" field="name">
                  <a-input
                    v-model="searchForm.name"
                    :placeholder="$t('config.form.name.placeholder')"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item :label="$t('config.form.configKey')" field="configKey">
                  <a-input
                    v-model="searchForm.configKey"
                    :placeholder="$t('config.form.configKey.placeholder')"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item :label="$t('config.form.type')" field="type">
                  <a-select
                    v-model="searchForm.type"
                    :placeholder="$t('config.form.type.placeholder')"
                    allow-clear
                    style="width: 100%"
                  >
                    <a-option
                      v-for="item in sys_yes_no"
                      :value="item.value"
                      :key="item.value"
                    >{{ item.label }}</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-space>
                  <a-button type="primary" @click="search">
                    <template #icon>
                      <icon-search />
                    </template>
                    {{ $t('searchTable.form.search') }}
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    {{ $t('searchTable.form.reset') }}
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
          <a-divider style="margin-top: 0" />
          <!-- 操作栏 -->
          <Operate
            :size="size"
            :columns="columns"
            :created="created"
            @createData="formRef.onOpen(null)"
            @search="search"
            @handleSelectDensity="handleSelectDensity"
            @handleCloneColumns="handleCloneColumns"
          ></Operate>
          <!-- 表格 -->
          <a-table
            row-key="id"
            :loading="loading"
            :pagination="pagination"
            :columns="cloneColumns"
            :data="renderData"
            :size="size"
            column-resizable
            :bordered="{cell:true}"
            @page-change="onPageChange"
            @page-size-change="onPageSizeChange"
          >
            <template #type="{ record }">
              <dict-tag :options="sys_yes_no" :value="record.type" :showDict="true" />
            </template>
            <template #operations="{ record }">
              <a-space>
                <a-button
                  type="text"
                  v-permission="'sys:config:update'"
                  @click="formRef.onOpen(record)"
                >{{ $t('searchTable.columns.operations.update') }}</a-button>
                <a-button
                  status="danger"
                  type="text"
                  v-permission="'sys:config:remove'"
                  @click="deleteData(record.id)"
                >{{ $t('searchTable.columns.operations.delete') }}</a-button>
              </a-space>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </a-card>
    <Form ref="formRef" @onSearch="search" />
  </div>
</template>
<script setup lang="ts">
import { ref, getCurrentInstance } from 'vue';
import { useI18n } from 'vue-i18n';
import { Modal, Message } from '@arco-design/web-vue';
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';

import { COLUMNS } from './hooks/columns.ts';

import {
  pageConfig,
  deleteConfig,
  ConfigParams,
  ConfigData,
} from '@/api/sys/config';

import Operate from '@/components/operate/index.vue';
import Form from '@/views/sys/config/components/form.vue';

const { t } = useI18n();

// 密度设置
const size = ref<any>('medium');
const handleSelectDensity = (val: any) => {
  size.value = val;
};

// 列设置
type Column = TableColumnData & { checked?: true };
const cloneColumns = ref<Column[]>([]);
const handleCloneColumns = (val: Column[]) => {
  cloneColumns.value = val;
};

// 定义表格列
const columns = ref<TableColumnData[]>(COLUMNS as TableColumnData[]);

// 初始化字典信息
const app = getCurrentInstance();
const { sys_yes_no } = app?.proxy?.useDict('sys_yes_no');
// 校验是否有新增权限
const created = app?.proxy?.hasPermission('sys:config:save');

// 定义搜索表单对象
const searchForm = ref<ConfigParams>({});
const searchFormRef = ref();
const formRef = ref();

// 定义数据源
const renderData = ref<ConfigData[]>();

// 加载按钮
const loading = ref(false);

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50, 100, 200, 500],
});

// 分页切换
const onPageChange = (current: number) => {
  pagination.value.current = current;
  search();
};
// 每页条数切换
const onPageSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  search();
};

// 重置
const reset = () => {
  searchFormRef.value.resetFields();
  Object.assign(searchForm, {});
  search();
};

//查询
const search = async () => {
  searchForm.value.current = pagination.value.current;
  searchForm.value.size = pagination.value.pageSize;
  fetchData(searchForm.value);
};

// 接口查询 - 获取列表
const fetchData = async (searchForm) => {
  loading.value = true;
  try {
    const { data } = await pageConfig(searchForm);
    renderData.value = data?.records ? data.records : [];
    pagination.value.total = data?.total ? data.total : 0;
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    loading.value = false;
  }
};

// 删除数据
const deleteData = (ids: any) => {
  Modal.confirm({
    title: t('operations.delete.title'),
    content: '',
    onOk() {
      loading.value = true;
      deleteConfig(ids)
        .then(() => {
          Message.success(t('operations.delete.success'));
          search();
        })
        .finally(() => {
          loading.value = false;
        });
    },
  });
};

// 初始化操作
const initData = async () => {
  await search();
};
initData();
</script>
